#coding=utf-8
import json
from urllib.error import URLError
from urllib.request import Request, ProxyHandler, HTTPHandler, build_opener, install_opener
from urllib.request import urlopen
from urllib.parse import urlencode

import math

import time

from catch.read_file import read

#根据用户id发送消息

def send(content,proxy_add,uid):
    try:
        url='https://m.weibo.cn/msgDeal/sendMsg?'
        cookie_file=open('../file/cookies.txt','r')
        cook=cookie_file.readline()
        print(cook)
        Referer='https://m.weibo.cn/msg/chat?uid=%s'%uid

        head={'Accept':'application/json',
              # 'Accept-Encoding':'utf-8;q=0.8',
              # 'Accept-Language':'zh-CN,zh;q=0.8',
              # 'Connection':'keep-alive',
              # 'Content-Length':46,
              'Content-Type':'application/x-www-form-urlencoded',
              'Host':'m.weibo.cn',
              'Origin':'https://m.weibo.cn',
              'Referer':Referer,
              'User-Agent':'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Mobile Safari/537.36',
              'X-Requested-With':'XMLHttpRequest',
              'Cookie':cook}

        parm={'fileId':'null','uid':uid,'st':'268255','content':content}
        data_parm=urlencode(parm).encode('utf-8')
        print(data_parm)

        proxy = ProxyHandler({'http': proxy_add})
        opener = build_opener(proxy, HTTPHandler(debuglevel=1))
        install_opener(opener)

        request=Request(data=data_parm,url=url,headers=head)
        reqspon=urlopen(request).read().decode('utf-8')
        data=json.loads(reqspon)
        print(data)
    except URLError as e:
        if hasattr(e,'code'):
            print(e.code)
        if hasattr(e,'reason'):
            print(e.reason)
        print(e)

if __name__=='__main__':

    file=open('../file/fans.txt','r')
    fans=file.readlines()
    for f in fans:
        fan=f.replace('\n','')
        print(fan)
        ip = read()
        print(ip)
        content="""亲~您好，关注@淘省钱淘宝优惠券，领取更多淘寶天貓内部优惠券"""
        send(content,ip,fan)
        time.sleep(3)